package com.sfx.算法专题.链表.双指针;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-30
 * Time: 15:44
 */
public class Code_2_getKthFromEnd {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    static class Solution {
        public ListNode getKthFromEnd(ListNode head, int k) {
            ListNode fast = head;
            ListNode slow = head;
            //快指针先走k步
            while(fast != null && k > 0) {
                fast = fast.next;
                k--;
            }
            while(fast != null) {
                fast = fast.next;
                slow = slow.next;
            }
            // k > 链表的长度这个情况
            return k == 0 ? slow : null;
        }
    }
}